﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Fayshine.VA.Helpers;
using Fayshine.VA.Models;
using Fayshine.VA.RIAService.Web;
using Fayshine.VA.ViewModels;
using Visifire.Charts;
using LocalBusyIndicator = Fayshine.VA.Controls.BusyIndicator;

namespace Fayshine.VA.Views.SearchStatistics.Week
{
    /// <summary>
    /// 周各门客流进出表
    /// </summary>
    public partial class WeekGateStatistics : Page
    {

        private WeekReportViewModel m_ViewModel;

        public WeekGateStatistics()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(WeekGateStatistics_Loaded);
        }

        private void WeekGateStatistics_Loaded(object sender, RoutedEventArgs e)
        {
            LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
            indicator.IsBusy = true;

            startDatePicker.SelectedDate = DateTime.Now;

            m_ViewModel = new WeekReportViewModel();
            m_ViewModel.ResetHisotryChartEvent += new ResetHistoryChartEventHandler(m_ViewModel_ResetHisotryChartEvent);
            m_ViewModel.AppendHistoryPassengerFlow += new AppendHistoryPassengerFlowEventHandler(m_ViewModel_AppendHistoryPassengerFlow);
            this.DataContext = m_ViewModel;

            m_ViewModel.GetAllAreas();
        }

        void m_ViewModel_AppendHistoryPassengerFlow(string title, bool isIn, List<HistoryPassengerFlow> firstHistoryPassengerFlow, List<HistoryPassengerFlow> secondHistoryPassengerFlow)
        {
            this.Dispatcher.BeginInvoke(delegate()
            {
                var source = m_ViewModel.WeekPassengerFlows.OrderBy(b => b.DisplayTitle);
                this.dataGrid.ItemsSource = source;

                //Chart title
                bool isSingleShop = m_ViewModel.CheckedAreas.Count == 1;
                isIn = cmbInorOut.SelectedIndex == 0 ? true : false;
                string subTitle = string.Format("{0}一周每日{1}客流对比",
                    isSingleShop ? "各门" : "各店铺",
                    cmbInorOut.SelectedIndex == 0 ? "进" : "出");

                DateTime dateTime = new DateTime(startDatePicker.SelectedDate.Value.Year, startDatePicker.SelectedDate.Value.Month,
                                          startDatePicker.SelectedDate.Value.Day);
                DateTime startTime = dateTime;
                DateTime endTime = dateTime;
                m_ViewModel.GetWeekStartAndEndTime(dateTime, out startTime, out endTime);
                string selectedAreas = string.Empty;
                if (isSingleShop)
                {
                    selectedAreas = string.Format("({0})", m_ViewModel.CheckedAreas[0].Name);
                }
                else
                {
                    selectedAreas = m_ViewModel.GetCheckedAreasText();
                }

                // string title1 = GetChartSubTitle();
                Title vcChart1Title = new Visifire.Charts.Title();

                vcChart1Title.Text = string.Format("{0}至{1}{2}{3}",
                   startTime.ToShortDateString(),
                   endTime.AddDays(-1).ToShortDateString(),
                   subTitle, selectedAreas);

                vcChart1.Titles.Add(vcChart1Title);

                // endof chart title

                RenderAs renderAs = cmbStyle.SelectedIndex == 0 ? RenderAs.Line : RenderAs.Column;
                string chartTitle = string.Empty;
                while (startTime < endTime)
                {
                    chartTitle = startTime.ToShortDateString() + FayshineManager.Instance.GetWeekDayString(startTime.DayOfWeek);
                    DataSeries series = ChartHelper.GetDataSeries(renderAs, chartTitle, ChartValueTypes.Auto);
                    series.DataMappings.Add(ChartHelper.GetDataMapping("AxisXLabel", "DisplayTitle"));
                    switch (startTime.DayOfWeek)
                    { 
                        case DayOfWeek.Monday:
                            if (isIn)
                            {
                                series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "MonDayInCount"));
                            }
                            else
                            {
                                series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "MonDayOutCount"));
                            }
                            break;
                        case DayOfWeek.Tuesday:
                            if (isIn)
                            {
                                series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "TueDayInCount"));
                            }
                            else
                            {
                                series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "TueDayOutCount"));
                            }
                            break;
                        case DayOfWeek.Wednesday:
                            if (isIn)
                            {
                                series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "WedDayInCount"));
                            }
                            else
                            {
                                series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "WedDayOutCount"));
                            }
                            break;
                        case DayOfWeek.Thursday:
                            if (isIn)
                            {
                                series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "ThuDayInCount"));
                            }
                            else
                            {
                                series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "ThuDayOutCount"));
                            }
                            break;
                        case DayOfWeek.Friday:
                            if (isIn)
                            {
                                series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "FriDayInCount"));
                            }
                            else
                            {
                                series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "FriDayOutCount"));
                            }
                            break;
                        case DayOfWeek.Saturday:
                            if (isIn)
                            {
                                series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "SatDayInCount"));
                            }
                            else
                            {
                                series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "SatDayOutCount"));
                            }
                            break;
                        case DayOfWeek.Sunday:
                            if (isIn)
                            {
                                series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "SunDayInCount"));
                            }
                            else
                            {
                                series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "SunDayOutCount"));
                            }
                            break;
                    }
                    series.DataSource = source;
                    vcChart1.Series.Add(series);
                    startTime = startTime.AddDays(1);
                }

                
                LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
                indicator.IsBusy = false;

            });
        }

        private void m_ViewModel_ResetHisotryChartEvent()
        {
            this.Dispatcher.BeginInvoke(delegate()
            {
                if (vcChart1 != null)
                {
                    vcChart1.AxesX.Clear();
                    vcChart1.TrendLines.Clear();
                    vcChart1.Series.Clear();
                    vcChart1.Titles.Clear();
                }
            });
        }

        private void cmbAreas_DropDownClosed(object sender, EventArgs e)
        {
            if (m_ViewModel != null)
            {
                m_ViewModel.AreaExtends.each(a => a.IsSelected = false);

                var selectItem = cmbAreas.SelectedItem as AreaExtend;
                if (selectItem != null)
                {
                    selectItem.IsSelected = true;
                }

                List<area> selectedArea = new List<area>();
                var selectAreaExt = m_ViewModel.AreaExtends.Where(a => a.IsSelected).ToList();
                selectAreaExt.ForEach(b =>
                {
                    area temp = b.Tag as area;
                    selectedArea.Add(temp);
                });

                m_ViewModel.SelectAreasChanged(selectedArea);

            }
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            string msg = string.Empty;
            m_ViewModel.UpdateCheckedAreas();

            if (!FayshineManager.Instance.ValidateAreaGateInputs(m_ViewModel.CheckedAreas,
                m_ViewModel.CheckedGates, ref msg))
            {
                MessageBox.Show(msg);
            }
            else
            {
                DateTime dateTime = new DateTime(startDatePicker.SelectedDate.Value.Year, startDatePicker.SelectedDate.Value.Month,
                                                 startDatePicker.SelectedDate.Value.Day);
                LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
                indicator.IsBusy = true;
                m_ViewModel.RefreshWeekGateReport(true, dateTime);
            }
        }

        private DataSeries GetDataSeries(string title, bool isIn, RenderAs randerAs, List<HistoryPassengerFlow> source)
        {
            DataSeries series = ChartHelper.GetDataSeries(randerAs, title, ChartValueTypes.Auto);
            series.DataMappings.Add(ChartHelper.GetDataMapping("AxisXLabel", "DisplayTitle"));
            if (isIn)
            {
                series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "InCount"));
            }
            else
            {
                series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "OutCount"));
            }
            series.DataSource = source;

            return series;
        }

        private string GetChartSubTitle()
        {
            string title1 = string.Empty;

            var selectAreaExts = m_ViewModel.AreaExtends.Where(a => a.IsSelected).ToList();
            if (selectAreaExts.Count == 1)
            {
                title1 = selectAreaExts[0].Name;
            }
            else if (selectAreaExts.Count > 1)
            {
                title1 = "各店铺";
            }

            return title1;
        }

        private void btnExport_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog fsd = new SaveFileDialog();
            fsd.Filter = "PDF (*.pdf)|*.pdf|*PNG (*.png)|*.png";

            if (fsd.ShowDialog() == true)
            {
                LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
                indicator.IsBusy = true;
                this.Dispatcher.BeginInvoke(delegate()
                {
                    FayshineManager.Instance.ExportToDisk(fsd, spContent);
                });
            }
        }

    }
}
